﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Acando.Dynamics.CRM.Silverlight.Library.MetaSdk;
using System.Collections.Generic;
using System.ServiceModel;
using System.Linq;
using Acando.Dynamics.CRM.Silverlight.Library.Interfaces;

namespace Acando.Dynamics.CRM.Silverlight.Library.Helper
{
    public class MetaSdkLookupTypesHelper
    {
        private int ManyToOneRelationshipsCounter = 0;
        private List<EntityMetadata> responseList = new List<EntityMetadata>();
        private List<String> ReferencedEntitiesList = new List<string>();

        public delegate void MetadataLoadedHandler(EntityMetadata metadata);
        public event MetadataLoadedHandler MetadataLoaded;

        public delegate void GetPossibleLookupTypesHandler(List<EntityMetadata> metadataList);
        public event GetPossibleLookupTypesHandler GetPossibleLookupTypesCompleted;

        
        public void GetPossibleLookupTypes(EntityMetadata entity, string attributeLogicalName, IMetaDataLayer metadatalayer)
        {
            
            //MetadataCache metaDataCache = new MetadataCache();
            //metaDataCache.MetadataLoaded += new MetadataCache.MetadataLoadedHandler(metaDataCache_MetadataLoaded);


            this.ReferencedEntitiesList.AddRange((from relationship in entity.ManyToOneRelationships
                                                  where relationship.ReferencingAttribute == attributeLogicalName.Replace("ownerid", "owninguser")
                                                  select relationship.ReferencedEntity));

            this.ManyToOneRelationshipsCounter = ReferencedEntitiesList.Count;

            foreach (var reference in this.ReferencedEntitiesList)
                //metaDataCache.LoadMetadata(reference);
                metadatalayer.LoadMetaData(reference, loadmetadataCallback);
        }

        void loadmetadataCallback(EntityMetadata metadata)
        {
            this.responseList.Add(metadata);

            if (responseList.Count == this.ManyToOneRelationshipsCounter)
                this.GetPossibleLookupTypesCompleted(responseList);
        }
    }
}
